package org.glut.wechat.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;

@Component
public class AliOssUtils {
    private static final Logger log = LoggerFactory.getLogger(AliOssUtils.class);

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.access-key-id}")
    private String accessKeyId;
    @Value("${aliyun.oss.access-key-secret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;
    @Value("${aliyun.oss.video-prefix}")
    private String videoPrefix;

    private OSS ossClient;

    @PostConstruct
    public void init() {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        log.info("OSS客户端初始化完成，endpoint：{}", endpoint);
    }

    // 新增：上传视频文件到OSS
    public void uploadVideoFile(String fileName, MultipartFile file) throws IOException {
        String key = videoPrefix + fileName;
        // 创建元数据对象，设置Content-Type
        ObjectMetadata metadata = new ObjectMetadata();
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if ("mp4".equals(fileExtension)) {
            metadata.setContentType("video/mp4");
        } else if ("webm".equals(fileExtension)) {
            metadata.setContentType("video/webm");
        } else if ("ogg".equals(fileExtension)) {
            metadata.setContentType("video/ogg");
        } else {
            metadata.setContentType("video/mp4"); // 默认设置为mp4
        }

        PutObjectRequest request = new PutObjectRequest(bucketName, key, file.getInputStream(), metadata);
        ossClient.putObject(request);
    }

    public String getVideoUrl(String fileName) {
        String key = videoPrefix + fileName;
        log.info("OSS视频路径：bucket={}，key={}", bucketName, key);

        Date expiration = new Date(System.currentTimeMillis() + 24 * 3600 * 1000);
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        String videoUrl = url.toString();

        log.info("生成OSS视频URL：{}", videoUrl);
        return videoUrl;
    }

    @PreDestroy
    public void destroy() {
        if (ossClient != null) {
            ossClient.shutdown();
            log.info("OSS客户端已关闭");
        }
    }

    public String getDirectVideoUrl(String fileName) {
        String key = videoPrefix + fileName;
        log.info("OSS视频路径：bucket={}，key={}", bucketName, key);
        // 生成不带签名的URL（需确保OSS bucket设置了公共读权限）
        return "https://" + bucketName + "." + endpoint + "/" + key;
    }
}